﻿using System;
using System.Data.Objects.DataClasses;
using System.Reflection;
using CarTrackr.Data.Attributes;


namespace  CarTrackr.Data
{
    public static  class  Converter
    {

        public static  T ToEntity<T>(object  businessObj)
        {
            PropertyInfo[] properties = businessObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            T entity =(T) Activator.CreateInstance(typeof(T));
            

            foreach (PropertyInfo property in properties)
            {
                if (IsPropertyOfDbField(property))
                {
                    PropertyInfo entityProperty = entity.GetType().GetProperty(GetPropertyDbFieldName(property));

                    if (entityProperty != null)
                    {

                        entityProperty.SetValue(entity, property.GetValue(businessObj, null), null);

                    }

                }

            }

            return entity;
             

        }


        public static T ToBusinessBase<T>(object obj)
         {
             PropertyInfo[] properties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

             T businessObj = (T)Activator.CreateInstance(typeof(T));

             foreach(PropertyInfo property in properties)
             {
                     if (IsPropertyOfDbField(property))
                     {
                           PropertyInfo entityProperty = obj.GetType().GetProperty(GetPropertyDbFieldName(property));

                           if (entityProperty != null)
                           {

                               property.SetValue(businessObj, entityProperty.GetValue(obj, null), null);

                           }

                      }

             }

             return businessObj;

         }


        private static bool IsPropertyOfDbField(PropertyInfo property)
        {
             object[] attributes = property.GetCustomAttributes(typeof (DbFieldAttribute), false);

             return attributes.Length == 1;

        }

        private static string GetPropertyDbFieldName(PropertyInfo property)
        {
            object[] attributes = property.GetCustomAttributes(typeof(DbFieldAttribute), false);

            return (attributes[0] as DbFieldAttribute).Name;

        }
    }
}
